//
//  RCPictureView.swift
//  RC-微博0305
//
//  Created by 任淳 on 16/3/12.
//  Copyright © 2016年 ReverChun. All rights reserved.
//

import UIKit

let cellIdentifier = "cellIdentifier"
let itemMargin:CGFloat = 5
let collectionMargin:CGFloat = 10


class RCPictureView: UICollectionView {

    var imageUrls:[NSURL]? {
        didSet {
//            print("\(imageUrls) ===================================== =============")
            //一拿到图片的URL集合 就计算collectionView的大小
            let collectionSize = calculateCollectionSize()
            
            //MARK: 一定是updateConstraints  不能是make cell会错乱
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(collectionSize)
            }
            //MARK: 刷新集合视图
            reloadData()
        }
    }
    
    func calculateCollectionSize()->CGSize {
        
        let imageCount = imageUrls?.count ?? 0
        
        let collectionMax = UIScreen.mainScreen().bounds.width - 2 * collectionMargin
        let itemWidth = (collectionMax - 2 * itemMargin) / 3
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //0张图片时
        if imageCount == 0 {
            return CGSizeZero
        }
        
        //1张图片时 itemSize = collectionSize
        if imageCount == 1 {
         //MARK: 以后处理
            let size = CGSizeMake(150, 200)
            layout.itemSize = size
            return size
        }
        
        if imageCount == 4 {
            let width = 2 * itemWidth + itemMargin
            return CGSizeMake(width, width)
        }
        
        //其他多张图片
        //确定行数  根据图片数量确定有多少行
        /*
        1,2,3   -> 1
        4,5,6   -> 2
        7,8,9   -> 3
        */

        let lines = CGFloat((imageCount - 1)/3 + 1)
        let conHeight = lines * itemWidth + (lines - 1) * itemMargin
        return CGSizeMake(collectionMax, conHeight)
        
    }
    
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor.whiteColor()
        
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 5
        
        //注册cell
        self.registerClass(RCCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
        self.dataSource = self
        self.delegate = self
        
        //设置点击顶部状态栏 不能够滚动到顶部
        self.scrollsToTop = false
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    
}
//代理方法
extension RCPictureView:UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageUrls?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //使用前必须注册
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! RCCollectionViewCell

//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        
        cell.imageUrl = imageUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //使用SDPhotoBrowser的固定步骤 下面还要实现两个代理方法
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = imageUrls?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
    
}
//遵守相关的协议
extension RCPictureView:SDPhotoBrowserDelegate {
    //返回高清图片的url对象
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = imageUrls![index].absoluteString
        let largeStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
        let url = NSURL(string: largeStr)
        
        return url
    }
    
    //返回cell占位图的iamge对象
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage!{
     
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        if let cell = cellForItemAtIndexPath(indexPath) as? RCCollectionViewCell {

            return cell.picture.image
        }
            return nil
    }
    
}
